package com.demo.wormhole.component.hystrix.callable;

import com.demo.wormhole.core.context.WormholeContext;
import com.demo.wormhole.core.context.WormholeContextHolder;

import java.util.concurrent.Callable;

public final class DelegatingWormholeContextCallable<V> implements Callable<V> {
    private final Callable<V> delegate;
    // 用户信息上下文（根据项目实际情况定义ThreadLocal上下文）
    private WormholeContext orginWormholeContext;
    
    public DelegatingWormholeContextCallable(Callable<V> delegate,
                                             WormholeContext wormholeContext) {
        this.delegate = delegate;
        this.orginWormholeContext = wormholeContext;
    }
    
    @Override
    public V call() throws Exception {
        //防止线程复用销毁ThreadLocal的数据
        WormholeContextHolder.invalidContext();
        // 将当前的用户上下文设置进Hystrix线程的TreadLocal中
        WormholeContextHolder.setContext(orginWormholeContext);
        try {
            return delegate.call();
        } finally {
            // 执行完毕，记得清理ThreadLocal资源
            WormholeContextHolder.invalidContext();
        }
    }
    
    public static <V> Callable<V> create(Callable<V> delegate,
                                         WormholeContext wormholeContext) {
        return new DelegatingWormholeContextCallable<V>(delegate, wormholeContext);
    }
}
